from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import List, Optional

mcp = FastMCP("Docker Engine MCP Server")

"""
Docker Engine MCP Server

面向软件：docker-engine

MCP tools 列表：
1. docker_service_restart - 重启 docker 服务
   参数：无
   返回：执行结果的 JSON 结构

2. docker_service_enable - 启用 docker 服务
   参数：无
   返回：执行结果的 JSON 结构

3. docker_service_log_check - 检查 docker 服务日志中的错误信息
   参数：since_time (str) - 日志起始时间，service_name (str) - 服务名称
   返回：执行结果的 JSON 结构

4. docker_service_reload - 重新加载 docker 服务配置
   参数：log_level (str) - 日志级别，默认为 "info"
   返回：执行结果的 JSON 结构
"""

@mcp.tool()
def docker_service_restart() -> dict:
    """
    重启 docker 服务
    
    参数：无
    
    返回 JSON 结构：
    {
        "success": bool,
        "command": str,
        "exit_code": int,
        "stdout": str,
        "stderr": str
    }
    """
    try:
        # 重启 docker 服务
        result = subprocess.run(
            ["systemctl", "restart", "docker.service"],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": "systemctl restart docker.service",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": "systemctl restart docker.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def docker_service_enable() -> dict:
    """
    启用 docker 服务
    
    参数：无
    
    返回 JSON 结构：
    {
        "success": bool,
        "command": str,
        "exit_code": int,
        "stdout": str,
        "stderr": str
    }
    """
    try:
        # 启用 docker 服务
        result = subprocess.run(
            ["systemctl", "enable", "docker.service"],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": "systemctl enable docker.service",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": "systemctl enable docker.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def docker_service_log_check(since_time: str, service_name: str = "docker.service") -> dict:
    """
    检查 docker 服务日志中的错误信息
    
    参数：
    - since_time (str): 日志起始时间，格式如 "2024-01-01 00:00:00"
    - service_name (str): 服务名称，默认为 "docker.service"
    
    返回 JSON 结构：
    {
        "success": bool,
        "command": str,
        "exit_code": int,
        "stdout": str,
        "stderr": str
    }
    """
    try:
        # 检查服务日志中的错误信息
        result = subprocess.run(
            [
                "journalctl", 
                "--since", since_time, 
                "-u", service_name,
                "|", 
                "grep", "-i", "fail\\|error",
                "|",
                "grep", "-v", "level=warning\\|level=info\\|no OpenTelemetry endpoint: skip plugin"
            ],
            shell=True,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": f"journalctl --since {since_time} -u {service_name} | grep -i 'fail\\|error' | grep -v 'level=warning\\|level=info\\|no OpenTelemetry endpoint: skip plugin'",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": f"journalctl --since {since_time} -u {service_name} | grep -i 'fail\\|error' | grep -v 'level=warning\\|level=info\\|no OpenTelemetry endpoint: skip plugin'",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def docker_service_reload(log_level: str = "info") -> dict:
    """
    重新加载 docker 服务配置
    
    参数：
    - log_level (str): 日志级别，默认为 "info"
    
    返回 JSON 结构：
    {
        "success": bool,
        "command": str,
        "exit_code": int,
        "stdout": str,
        "stderr": str
    }
    """
    try:
        # 启动 docker 服务
        start_result = subprocess.run(
            ["systemctl", "start", "docker.service"],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        if start_result.returncode != 0:
            return {
                "success": False,
                "command": "systemctl start docker.service",
                "exit_code": start_result.returncode,
                "stdout": start_result.stdout,
                "stderr": start_result.stderr
            }
        
        # 修改 docker 服务配置
        sed_result = subprocess.run(
            ["sed", "-i", f"s/dockerd/dockerd --log-level={log_level}/g", "/usr/lib/systemd/system/docker.service"],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        if sed_result.returncode != 0:
            return {
                "success": False,
                "command": f"sed -i 's/dockerd/dockerd --log-level={log_level}/g' /usr/lib/systemd/system/docker.service",
                "exit_code": sed_result.returncode,
                "stdout": sed_result.stdout,
                "stderr": sed_result.stderr
            }
        
        # 重新加载 systemd 配置
        daemon_reload_result = subprocess.run(
            ["systemctl", "daemon-reload"],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        if daemon_reload_result.returncode != 0:
            return {
                "success": False,
                "command": "systemctl daemon-reload",
                "exit_code": daemon_reload_result.returncode,
                "stdout": daemon_reload_result.stdout,
                "stderr": daemon_reload_result.stderr
            }
        
        # 重新加载 docker 服务
        reload_result = subprocess.run(
            ["systemctl", "reload", "docker.service"],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": reload_result.returncode == 0,
            "command": f"systemctl reload docker.service (with log-level={log_level})",
            "exit_code": reload_result.returncode,
            "stdout": reload_result.stdout,
            "stderr": reload_result.stderr
        }
        
    except Exception as e:
        return {
            "success": False,
            "command": "docker service reload sequence",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()